package com.changxianggu.cloud.edu.tool.core;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.changxianggu.cloud.edu.tool.entity.gen.GenCodeEntity;

import java.util.Map;

/**
 * 抽取名字和代码的核心类
 *
 * @author liuyuantao
 */
public class ExtraNameCodeUtil {

    public static final int DIVISION_NUM = 9;


    /**
     * 提取名字
     *
     * @param dataObj
     * @param nameKey
     * @return
     */
    public static String extraObjName(Map<String, Object> dataObj, String nameKey) {
        String targetName = "";
        if (StrUtil.isBlank(nameKey) || MapUtil.isEmpty(dataObj)) {
            return targetName;
        }
        Object o = dataObj.get(nameKey);
        if (o == null) {
            return targetName;
        }
        targetName = o.toString().trim();
        return targetName;
    }


    /**
     * 生成代码
     *
     * @param parentCode
     * @param current
     * @param allResultDataMap
     * @return
     */
    public static GenCodeEntity genCode4Data(String parentCode, int current, Map<String, Object> allResultDataMap) {
        String targetCode = "";
        GenCodeEntity genCodeEntity = new GenCodeEntity();
        //需要生成代码
        boolean existCode = true;
        while (existCode) {
            String codeResult = genCode(parentCode, current);
            //检查生成的代码是否存在重复
            Object existObj = allResultDataMap.get(codeResult);
            if (existObj == null) {
                //生成代码成功
                targetCode = codeResult;
                existCode = false;
                genCodeEntity.setCurrentCount(current);
                genCodeEntity.setCode(targetCode);
            } else {
                current++;
            }
        }
        return genCodeEntity;
    }

    /**
     * 生成代码方法
     *
     * @param parentCode
     * @param current
     * @return
     */
    static String genCode(String parentCode, int current) {
        if (current > DIVISION_NUM) {
            return parentCode + current;
        } else {
            return parentCode + "0" + current;
        }
    }
}
